import pygame as pg
from .. import setup as su,tools

DIRECTDICT = {pg.K_LEFT  : (-1, 0),
              pg.K_RIGHT : ( 1, 0),
              pg.K_UP    : ( 0,-1),
              pg.K_DOWN  : ( 0, 1)}

class Player(object):
    def __init__(self,rect,speed,direction=pg.K_RIGHT):
        self.rect = pg.Rect(rect)
        self.speed = speed
        self.direction = direction
        self.oldy = None
        self.dir_stack = []
        self.walk = False
        self.redraw = False
        self.spritesheet = su.GFX["skelly"]
        self.image = None
        self.frame_inds = [[0,0],[1,0],[2,0],[3,0]]
        self.frame  = 0
        self.frames = []
        self.timer = 0.0
        self.fps   = 7.0
        self.walkframes = []
        self.get_images()
        self.walkframe_dict = self.make_frame_dict()
        self.adjust_images()
    def get_images(self):
        """Get the desired images from the sprite sheet."""
        for cell in self.frame_inds:
            loc = ((self.rect.width*cell[0],self.rect.height*cell[1]),self.rect.size)
            self.frames.append(self.spritesheet.subsurface(loc))
    def make_frame_dict(self):
        frames = {pg.K_LEFT : [self.frames[0],self.frames[1]],
                  pg.K_RIGHT: [pg.transform.flip(self.frames[0],True,False),
                               pg.transform.flip(self.frames[1],True,False)],
                  pg.K_DOWN : [self.frames[3],
                               pg.transform.flip(self.frames[3],True,False)],
                  pg.K_UP   : [self.frames[2],
                               pg.transform.flip(self.frames[2],True,False)]}
        return frames
    def adjust_images(self):
        if self.direction != self.oldy:
            self.walkframes = self.walkframe_dict[self.direction]
            self.oldy = self.direction
            self.redraw = True
        self.make_image()
    def make_image(self):
        if self.redraw or pg.time.get_ticks()-self.timer > 1000/self.fps:
            if self.walk:
                self.frame = (self.frame+1) % len(self.walkframes)
                self.image = self.walkframes[self.frame]
            self.timer = pg.time.get_ticks()
        if not self.image:
            self.image = self.walkframes[self.frame]
        self.redraw = False
    def update(self,Surf):
        """Updates our player appropriately every frame."""
        self.walk = bool(self.dir_stack)
        self.adjust_images()
        if self.walk:
            self.rect.x += self.speed*DIRECTDICT[self.dir_stack[-1]][0]
            self.rect.y += self.speed*DIRECTDICT[self.dir_stack[-1]][1]
        Surf.blit(self.image,self.rect)

class FourDir(tools._State):
    def __init__(self):
        tools._State.__init__(self)
        self.Player = Player((250,250,50,50),3)  #Our Player instance
        self.title = self.render_font("Fixedsys500c",40,"4-Direction Movement",(0,255,255))
        self.title_rect = self.title.get_rect(center=(su.SCREEN_RECT.centerx,75))
        self.escape_txt = (self.render_font("Fixedsys500c",20,
                            "[Press ESCAPE to return to menu]",(255,255,0)))
        self.escape_txt_rect = self.escape_txt.get_rect(center=(su.SCREEN_RECT.centerx,500))
        self.blink = False
        self.timer = 0.0
    def render_font(self,font,size,msg,color=(255,255,255)):
        RenderFont = pg.font.Font(su.FONTS[font],size)
        return RenderFont.render(msg,1,color)
    def get_event(self,event):
        if event.type == pg.KEYDOWN: #all key press events here.
            if event.key in DIRECTDICT:
                self.Player.dir_stack.append(event.key)
                self.Player.direction = self.Player.dir_stack[-1]
            elif event.key == pg.K_ESCAPE:
                self.next = "MENU"
                self.done = True
        elif event.type == pg.KEYUP: #all key-up events here
            if event.key in DIRECTDICT:
                self.Player.dir_stack.remove(event.key)
                if self.Player.dir_stack:
                    self.Player.direction = self.Player.dir_stack[-1]
    def cleanup(self):
        self.persist["location"] = self.Player.rect.center
        return tools._State.cleanup(self)
    def startup(self,persistant):
        tools._State.startup(self,persistant)
        if "location" in self.persist:
            self.Player.rect.center = self.persist["location"]
    def update(self,Surf,keys,mouse):
        Surf.fill((100,100,100)) #redraw background before player
        self.Player.update(Surf) #update the player
        Surf.blit(self.title,self.title_rect)
        if pg.time.get_ticks() - self.timer > 1000/5.0:
            self.blink = not self.blink
            self.timer = pg.time.get_ticks()
        if self.blink:
            Surf.blit(self.escape_txt,self.escape_txt_rect)